package com.mux.util.coder;


import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

import org.apache.commons.codec.binary.Base64;


/**
 * 编码+压缩
 * @author devin.chen
 *
 */
public class Base64ZipUtil {
	
//	压缩字符串
	public static String compressData(String data) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			DeflaterOutputStream zos = new DeflaterOutputStream(bos);
			zos.write(data.getBytes("GBK"));
			zos.close();
			return new String(getenBASE64inCodec(bos.toByteArray()));
		} catch (Exception ex) {
			ex.printStackTrace();
			return "ZIP_ERR";
		}
	}
	
//	使用apche codec对数组进行encode
	public static String getenBASE64inCodec(byte [] b) {
		if (b == null)
			return null;
		return new String((new Base64()).encode(b),Charset.forName("GBK"));
		//return new Base64().encodeAsString(b);
	}
	
	
	
	
//	base64转码为string
	
	public static byte[] getdeBASE64inCodec(String s)throws Exception {
		if (s == null)
			return null;
		return new Base64().decode(s.getBytes("GBK"));
	}
	
//	解码字符串
	public static String decompressData(String encdata) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			InflaterOutputStream zos = new InflaterOutputStream(bos);
			zos.write(getdeBASE64inCodec(encdata)); 
			zos.close();
			return new String(bos.toByteArray(),"GBK");
		} catch (Exception ex) {
			ex.printStackTrace();
			return "UNZIP_ERR";
		}
	}
	
	
	public static void main(String[] args) {
		Base64ZipUtil zwz = new Base64ZipUtil();
		String compString = zwz.compressData("中华人民共和国");
		System.out.println(compString);
		
		compString="eJx9T90KgjAYfZX4rhU2/9mrhIwxv2rkVLYZhHjbUwS9Qi9Vz9FUEOuiy8P5H8AZIRHYfgArarS8NUdgQGhSQLCQvBLOKyAiNA1JFkaxZzpx1dg4LnvrWo0GGA1Ats3kcFxVC15JIClJkiLP8ylWnlCeeYdGtV445ZJsLmvsAQ13Sn/1ZTsaMVIwGq+TNrVjudkp5icXUXv/6/Z8P+5/XyiHmmt0Yl38+6AWvcUFjeX4Ae/TX6I=";
		String decompString = zwz.decompressData(compString);
		System.out.println(decompString);
		
	}
}
